package com.github.hgkmail.hello.leetcode101.firstsearch;

import java.util.ArrayList;
import java.util.List;

//组合数 回溯法
public class LC77Combinations {
    //辅函数
    public void backtrack(int n, int k, int[] used, List<Integer> aCase, List<List<Integer>> res) {
        int len=aCase.size();
        if (len==k) {
            res.add(new ArrayList<>(aCase));
            return;
        }
        //从小往大安插数字，下一个数不应该比前一个数小
        int i = !aCase.isEmpty() ? aCase.get(len-1)+1 : 1;
        for (; i <= n; i++) {
            if (used[i]==1) {
                continue;
            }
            aCase.add(i);
            used[i]=1;
            backtrack(n, k, used, aCase, res);
            //还原
            aCase.remove(Integer.valueOf(i));
            used[i]=0;
        }
    }
    public List<List<Integer>> combine(int n, int k) {
        if (n<=0 || n<k) {
            return new ArrayList<>();
        }
        int[] used = new int[n+1];
        for (int i = 0; i < used.length; i++) {
            used[i]=0;
        }
        List<Integer> aCase = new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        backtrack(n, k, used, aCase, res);

        return res;
    }

    public static void main(String[] args) {
        System.out.println(new LC77Combinations().combine(4, 2));
    }
}
